package com.vision.shop.dao;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.vision.shop.model.Category;
import com.vision.shop.model.Pager;
import com.vision.shop.model.Product;
import com.vision.shop.model.ShopDi;
import com.vision.shop.model.ShopException;
import com.vision.shop.model.SystemContext;

public class ProductDao extends BaseDao<Product> implements IProductDao {
	private ICategoryDao categoryDao;
	@ShopDi
	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	@Override
	public void add(int cid, Product product) {
		Category c=categoryDao.load(cid);
		if(c==null){
			throw new ShopException("要添加的类别不存在");
		}
		product.setCategory(c);
		super.add(product);
	}

	@Override
	public void delete(int id) {
		// TODO 如果用户购买了该商品就不能删除,该商品存在订单也不能删除
		//如果可以删除商品的话需要删除商品的图片
		Product p=this.load(id);
		String image=p.getImage();
		String path=SystemContext.getRealpath()+"/img/";
		File f=new File(path+image);
		f.delete();
		super.delete(Product.class, id);
		
	}

	@Override
	public void update(int cid,Product product) {
		Category c=categoryDao.load(cid);
		if(c==null){
			throw new ShopException("要添加的类别不存在");
		}
		product.setCategory(c);
		super.update(product);

	}

	@Override
	public Product load(int id) {
		return super.load(Product.class, id);
	}

	@Override
	public Pager<Product> find(int cid, String name,int status) {
		Map<String,Object> params=new HashMap<String,Object>();
		if(cid>0){
			params.put("cid", cid);		
		}
		if(name!=null&&!"".equals(name.trim())){
			params.put("name", name);
		}
		if(status==1||status==-1){
			params.put("status", status);
		}
		return super.find(Product.class, params);
	}

	@Override
	public void addStock(int id, int num) {
		Product product=this.load(id);
		product.setStock(product.getStock()+num);
		super.update(product);
	}

	@Override
	public void decreaseStock(int id, int num) {
		Product product=this.load(id);
		product.setStock(product.getStock()-num);
		super.update(product);
	}

	@Override
	public void changeStatus(int id) {
		Product product=this.load(id);
		if(product.getStatus()==-1){
			product.setStatus(1);
		}else{
			product.setStatus(-1);
		}
		this.update(product);
	}

	

}
